package com.spddr.pmos.oauth2;

import java.util.List;

import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.apache.cxf.jaxrs.utils.ExceptionUtils;
import org.apache.cxf.jaxrs.utils.JAXRSUtils;
import org.apache.cxf.message.Message;
import org.apache.cxf.rs.security.oauth2.filters.OAuthRequestInterceptor;
import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants;

/** 此拦截器额外做了一步工作，当没有找到 Authorization 头时再到 Cookie 中查找 access_token */
public class OauthRequestInterceptor extends OAuthRequestInterceptor {
	@Override
	protected String[] getAuthorizationParts(Message message) {
		HttpHeaders httpHeaders = getMessageContext().getHttpHeaders();

		List<String> headers = httpHeaders.getRequestHeader(HttpHeaders.AUTHORIZATION);
		if (null != headers && !headers.isEmpty()) {
			// HttpHeaders 中包含 Authorization，走常规流程
			return super.getAuthorizationParts(message);
		} else {
			// 在 Cookie 中查找 access_token
			Cookie cookie = httpHeaders.getCookies()
					.get(OAuthConstants.ACCESS_TOKEN);
			if (null != cookie) {
				// 只支持 Bearer 类型，此 cookie是由 @see cn.seqdata.jaxrs.oauth2.JaxrsOauthSignImpl 注入
				return new String[] { OAuthConstants.BEARER_AUTHORIZATION_SCHEME, cookie.getValue() };
			} else {
				ResponseBuilder rb = JAXRSUtils.toResponseBuilder(401);
				throw ExceptionUtils.toNotAuthorizedException(null, rb.build());
			}
		}
	}
}
